package com.resource.authoritymanage.load;

import com.resource.authoritymanage.config.R;
import com.resource.common.utils.AppResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/authority/common")
public class CommonController {

    @Value("${upload.path}")
    private String staticpath;
    String s= UUID.randomUUID().toString();

    @PostMapping("/upload")
    //这里的参数名要与名字一致,不能随便写
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        //file是一个临时文件，请求结束后就删除了
        String originalFilename = file.getOriginalFilename();//获取原始路径
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        //判断路径是否存在
        File file1 = new File(staticpath);
        if(!file1.exists()){
            file1.mkdirs();
          }
        file.transferTo(new File(staticpath+"\\"+s+originalFilename+substring));
        //返回
        return R.success(s+originalFilename+substring);
    }

    @GetMapping("/download")
    public void download(@RequestParam("name") String name, HttpServletResponse response) throws IOException {
        //利用输入输出路操作
        FileInputStream fileInputStream = new FileInputStream(new File(staticpath+"\\"+name));
            byte[] bytes=new byte[1024];
            int len=0;
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/png");
        while((len=fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        fileInputStream.close();
        outputStream.close();
    }

}
